package com.gqb.ssm.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by 小泽玛丽罗 on 2016/11/13.
 */
public class SqlSessionFactoryUtil {
    private  static SqlSessionFactory sqlSessionFactory=null;

    private static  final  Class CLASS_LOCK=SqlSessionFactoryUtil.class;

    /**
     * 私有化构造器，单利模式必备
     */
    private SqlSessionFactoryUtil(){}

    public  static SqlSessionFactory initSqlSessionFactory(){
        String resource="mybatis-config.xml";
        InputStream inputStream=null;
        try {
            inputStream= Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(sqlSessionFactory==null){
            synchronized (CLASS_LOCK){
                if(sqlSessionFactory==null)
                    sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
            }
            return sqlSessionFactory;
        }else{
            return sqlSessionFactory;
        }
    }

    public static SqlSession openSession(){
        if(sqlSessionFactory==null){
            initSqlSessionFactory();
        }
        return sqlSessionFactory.openSession();
    }

}
